package com.xoa.service.workflow.flowtype.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ibatis.common.resources.Resources;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.document.DocumentMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.*;
import com.xoa.dao.worldnews.NewsMapper;
import com.xoa.model.common.SysPara;
import com.xoa.model.department.Department;
import com.xoa.model.document.Document;
import com.xoa.model.document.DocumentModelWithBLOBs;
import com.xoa.model.document.DocumentWithBLOBs;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.users.UserPriv;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.*;
import com.xoa.model.worldnews.News;
import com.xoa.service.department.DepartmentService;
import com.xoa.service.syspara.SysParaService;
import com.xoa.service.users.UsersPrivService;
import com.xoa.service.users.UsersService;
import com.xoa.service.work.WorkService;
import com.xoa.service.workflow.flowtype.FlowFormTypeService;
import com.xoa.util.AjaxJson;
import com.xoa.util.CookiesUtil;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.dataSource.Verification;
import com.xoa.util.ipUtil.IpAddr;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by gsb on 2017/5/9.
 */
@Service
public class FlowFormTypeServiceImpl implements FlowFormTypeService {
    @Resource
    private FlowFormTypeMapper flowFormTypeMapper;
    @Resource
    private FlowTypeModelMapper typeModelMapper;

    @Resource
    private UsersService usersService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private UsersPrivService usersPrivService;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private FlowTypeModelMapper flowTypeModelMapper;
    @Resource
    private FlowRunMapper flowRunMapper;
    @Resource
    private WorkService workService;
    @Resource
    private UserPrivMapper userPrivMapper;

    @Resource
    private UsersMapper usersMapper;
    @Resource
    private FlowProcessMapper flowProcessMapper;
    @Resource
    private DocumentMapper documentMapper;
    @Resource
    private FlowRunPrcsMapper flowRunPrcsMapper;
    @Resource
    private NewsMapper newsMapper;
    @Resource
    private SysParaService sysParaService;

    @Override
    public ToJson<FlowFormType> qureyItemMax(Integer formId) {
        ToJson<FlowFormType> toJson = new ToJson<FlowFormType>(0, "");
        if (formId != null) {
            FlowFormType folw = flowFormTypeMapper.qureyItemMax(formId);
            if (folw != null) {
                toJson.setMsg("ok");
                toJson.setObject(folw);
            }
		/*if (folw!=null) {
		folw.setItemMax(folw.getItemMax()+1);
		int a= flowFormTypeMapper.updateItemMax(folw);
		if(a>0) {
		toJson.setMsg("ok");
		toJson.setObject(folw);
		}else{
			toJson.setMsg("err");
		}

		}*/

        } else {
            toJson.setMsg("err");
        }


        return toJson;
    }

    @Override
    public ToJson<TMacroCtrl> qureyCtrl(String controlId, String option, HttpServletRequest request, Integer fromId, Integer folwId,
                                        String runId, String prcsId, String flowPrcs, String company, String signlock, String PRCS_ID, String FLOW_PRCS, String sql, String sqlList) {
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        String userId = users.getUserId();
        Users users11 = usersMapper.selectUserByUId(users.getUid());
        Integer userPriv = users.getUserPriv();

        String[] strArray = null;
        ToJson<TMacroCtrl> json = new ToJson<TMacroCtrl>();
        TMacroCtrl tM = new TMacroCtrl();
        Date curDate = new Date();//获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(curDate);
        String date1 = sdf1.format(curDate);
        StringBuffer bb1 = new StringBuffer();
        StringBuffer bb2 = new StringBuffer();
        StringBuffer bb3 = new StringBuffer();
        StringBuffer bb4 = new StringBuffer();
        Map<String, Object> maps = new HashMap<String, Object>();
        //部门主管（本部门ID）
        Integer deptId = users.getDeptId();
       /*  Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);*/
        String sqlType = (String) request.getSession().getAttribute(
                "loginDateSouse");
        String sqlType1 = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        //ContextHolder.setConsumerType(sqlType);
        try {
            //数据库的链接
            Properties props = Resources.getResourceAsProperties("jdbc-sql.properties");
            String url = props.getProperty("url" + sqlType);
            String driver = props.getProperty("driverClassName");
            String username = props.getProperty("uname" + sqlType);
            String password = props.getProperty("password" + sqlType);
            Class.forName(driver).newInstance();
            Connection conn = (Connection) DriverManager.getConnection(url, username, password);
            List<Map<String, Object>> isExistSql_1 = null;
            HashMap list = new HashMap<>();
            if (sql != null && !sql.equals("") &&!sql.equals("undefined") ) {
                String[] mm = sql.split(";");
                for (int j = 0; j < mm.length; j++) {
                    String[] sqlEE = mm[j].split("-");
                    String Data = sqlEE[0];
                    String SqlNew = sqlEE[1];

                    isExistSql_1 = Verification.CheckIsExistSql(request, conn, driver, url, username, password, SqlNew, runId);
                    if (isExistSql_1 != null) {
                        list.put(Data, isExistSql_1);
                    }
                  /* suf.append(String.valueOf(isExistSql_1));
                   suf.append(";");*/
                    //list.add((Map<String, Object>) isExistSql_1);
                }
                tM.setSYS_SQL(list);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (tM.getControlId().equals(controlId)) {
            tM.setSYS_USERID(users.getUserId());//当前用户ID
            tM.setSYS_USERNAME(users.getUserName());//当前用户姓名
            List<Department> l = new ArrayList<Department>();
            l = departmentService.getFatherDept(users.getDeptId(), l);
            StringBuffer sb = new StringBuffer();
            for (int i = l.size() - 1; i >= 0; i--) {
                sb.append(l.get(i).getDeptName());
                if (i > 0) {
                    sb.append("/");
                }
            }
            tM.setSYS_DEPTNAME(sb.toString());//当前用户部门（长名称）
            tM.setSYS_DEPTNAME_SHORT(users.getDeptName());//当前用户部门（短名称）
            tM.setSYS_USERPRIV(users.getUserPrivName());//当前用户角色]
            if (users11.getSignImageId() != null && users11.getSignImageId() != null) {
                users11.setAttachment(GetAttachmentListUtil.returnAttachment(users11.getSignImageName(), users11.getSignImageId(), sqlType1, GetAttachmentListUtil.USER_IMAGE));
            }
            tM.setSYS_SIGN_IMAGE(users11.getAttachment());//用户签名
            if (!StringUtils.checkNull(users11.getUserPrivOther())) {
                StringBuffer stringBuffer = new StringBuffer();
                String[] strings = users11.getUserPrivOther().split(",");

                for (int i = 0; i < strings.length; i++) {
                    UserPriv userPriv1 = userPrivMapper.getUserPriv(Integer.parseInt(strings[i]));
                    if (userPriv1 != null) {
                        stringBuffer.append(userPriv1.getPrivName());
                        stringBuffer.append(",");
                    }
                }
                tM.setSYS_USERPRIVOTHER(stringBuffer.toString());//当前用户辅助角色（备注）
            }else{
                tM.setSYS_USERPRIVOTHER("");
            }


            tM.setSYS_USERNAME_DATE(users.getUserName() + " " + date1);//当前用户姓名+日期
            tM.setSYS_RUNDATETIME(users.getUserName() + " " + date);//当前用户姓名+日期+时间
            tM.setSYS_RUNDATE(users.getUserName() + " " + date1);//
            tM.setSYS_IP(IpAddr.getV4IP());//获取当前的IP地址
            FlowFormType folw = null;
            FlowTypeModel flowTypeModel = null;
            if (folwId != null && folwId != 0) {
                flowTypeModel = typeModelMapper.queryOneObject(folwId);
                fromId = flowTypeModel.getFormId();
            }

            if (fromId != null) {
                folw = flowFormTypeMapper.qureyItemMax(fromId);
            }
            if (folw != null) {
                tM.setSYS_FORMNAME(folw.getFormName());//表单名称
            }
            FlowTypeModel folw1 = null;
            if (folwId != null && fromId != null) {
                folw1 = flowTypeModelMapper.selectOnlyType(folwId, fromId);
            }
            FlowRun flowRun = null;
            if (!StringUtils.checkNull(runId)) {
                flowRun = flowRunMapper.find(Integer.parseInt(runId));
                tM.setSYS_RUNNAME(flowRun.getRunName());//工作名称/文号
                tM.setSYS_RUNIDDATE(runId + " " + date1);
            }
            if (folw1 != null) {
                tM.setSYS_AUTONUM(folw1.getAutoNum() + "");//文号计数器
                tM.setSYS_AUTONUM_YEAR(folw1.getAutoNumYear() + "");//文号计数器(按年编号)
                tM.setSYS_AUTONUM_MONTH(folw1.getAutoNumMonth() + "");//文号计数器(按月编号)
            }
            if (!StringUtils.checkNull(runId) && !StringUtils.checkNull(flowPrcs)) {
                AjaxJson ajaxJson = workService.findworkfeedback(request, runId, prcsId, flowPrcs, userId, company, signlock, PRCS_ID, FLOW_PRCS);
                tM.setSignText(ajaxJson.getObj());
            }
            Department department = departmentMapper.getFatherDept(deptId);
            //部门主管(本部门)
            String manag = department.getManager();
            //String assistant =department.getAssistantId();

            if (manag != null && !manag.equals("")) {
                String[] mm = manag.split(",");
                for (int j = 0; j < mm.length; j++) {
                    try {
                        String name2 = usersService.getUserNameById(mm[j], ",");
                        if (name2 != null) {
                            bb1.append(name2);
                            bb1.append(",");
                        }

                        if (!StringUtils.checkNull(String.valueOf(bb1))) {
                            tM.setSYS_MANAGER1(bb1.toString().substring(0, bb1.toString().length() - 1));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        String name2 = usersService.getUserNameById(mm[j]);
                        if (name2 != null) {
                            bb1.append(name2);
                            bb1.append(",");
                        }
                        if (!StringUtils.checkNull(String.valueOf(bb1))) {
                            tM.setSYS_MANAGER1(bb1.toString().substring(0, bb1.toString().length() - 1));
                        }

                    }


                }

            }
            //部门主管（上级部门）
            if (department.getDeptParent() != null && !department.getDeptParent().equals("")) {
                String parentId = departmentMapper.getDeptManagerIdByDeptId(department.getDeptParent());
                if (parentId != null && !parentId.equals("")) {
                    String[] depNa = parentId.split(",");
                    for (int b = 0; b < depNa.length; b++) {
                        //部门主管（上级部门主管的名称）
                        String userName = usersService.getUserNameById(depNa[b], ",");
                        if (userName != null) {
                            bb4.append(userName);
                            bb4.append(",");
                        }
                    }
                }
            }
            if (!StringUtils.checkNull(String.valueOf(bb4))) {
                tM.setSYS_MANAGER4(bb4.toString().substring(0, bb4.toString().length() - 1));
            }
            //上级主管领导
            String leader1 = department.getLeader1();
            if (leader1 != null && !leader1.equals("")) {
                String[] dd = leader1.split(",");
                for (int j = 0; j < dd.length; j++) {
                    try {
                        String name4 = usersService.findUsersByuid(Integer.parseInt(dd[j]));
                        if (name4 != null) {
                            bb2.append(name4);
                            bb2.append(",");

                        }
                        if (!StringUtils.checkNull(String.valueOf(bb2))) {
                            tM.setSYS_MANAGER2(bb2.toString().substring(0, bb2.toString().length() - 1));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        String name4 = usersService.getUserNameById(dd[j]);
                        if (name4 != null) {
                            bb2.append(name4);
                            bb2.append(",");

                        }
                        if (!StringUtils.checkNull(String.valueOf(bb2))) {
                            tM.setSYS_MANAGER2(bb2.toString().substring(0, bb2.toString().length() - 1));
                        }
                    }

                }
            }
            //存放去重后的字符串
            StringBuffer str5 = new StringBuffer();
            //部门主管（一级部门）
            List<Department> departments = departmentMapper.getDepartmentByParet();
            if (departments != null) {
                for (Department department1 : departments) {
                    //获取所有一级部门部门主管id串
                    String deptName = departmentMapper.getDeptManagerIdByDeptId(department1.getDeptId());
                    if (deptName != null && !deptName.equals("")) {
                        String[] depNa = deptName.split(",");
                        for (int b = 0; b < depNa.length; b++) {
                            //部门主管（一级部门主管名称）
                            String userName = usersService.getUserNameById(depNa[b], ",");
                            if (userName != null) {
                                bb3.append(userName);
                                bb3.append(",");
                            }
                        }


                    }
                }
                //定义一个空数组
                List<String> listR = new LinkedList<>();
                if (!StringUtils.checkNull(bb3.toString())) {
                    //定义数组
                    String[] substring = bb3.toString().split(",");
                    //数组转换成list
                    List<String> list = Arrays.asList(substring);
                    if (list != null) {
                        for (String str : list) {
                            //去重
                            if (!(listR.contains(str))) {
                                listR.add(str);
                            }
                        }
                    }

                    // 遍历
                    if (listR.size() > 0) {
                        for (String s : listR) {
                            str5.append(s + ",");
                        }
                    }
                }
                if (!StringUtils.checkNull(String.valueOf(str5))) {
                    tM.setSYS_MANAGER3(str5.toString().substring(0, str5.toString().length() - 1));
                }
            }

            /*
             * 下拉列表
             * */
            if (!StringUtils.checkNull(option)) {
                strArray = option.split(",");
                for (int j = 0; j < strArray.length; j++) {
                    if ("SYS_LIST_DEPT".equals(strArray[j])) {
                        List<Department> deptList = departmentService.getDatagrid();
                        tM.setSYS_LIST_DEPT(deptList);
                    }
                    if ("SYS_LIST_USER".equals(strArray[j])) {
                        List<Users> list = usersService.getAlluser(maps, 1, 5, false);
                        tM.setSYS_LIST_USER(list);
                    }
                    if ("SYS_LIST_PRIV".equals(strArray[j])) {
                        List<UserPriv> list = usersPrivService.getAllPriv(maps, 1, 5, false);
                        tM.setSYS_LIST_PRIV(list);
                    }
                    if ("SYS_LIST_PRIV_ONLY".equals(strArray[j])) {//宏控件主角色列表
                        List<UserPriv> list = usersPrivService.getAllPriv(maps, 1, 5, false);
                        tM.setSYS_LIST_PRIV_ONLY(list);
                    }
                    if ("SYS_LIST_PRIV_OTHER".equals(strArray[j])) {//宏控件辅助角色列表
                        List<UserPriv> list = new LinkedList<>();
                        Users users1 = usersMapper.getUsersByuserId(userId);
                        if (users1 != null) {
                            if (users1.getUserPrivOther() != null && !users1.getUserPrivOther().equals("")) {
                                String[] depNa = users1.getUserPrivOther().split(",");
                                for (int b = 0; b < depNa.length; b++) {
                                    UserPriv userPriv1 = userPrivMapper.getPrivName11(Integer.valueOf(depNa[b]));
                                    list.add(userPriv1);
                                }
                            }
                        }
                        tM.setSYS_LIST_PRIV_OTHER(list);
                    }
                    /*System.out.println("FlowFormTypeServiceImpl.qureyCtrl==>"+"SYS_LIST_PRCSUSER1".equals(strArray[j]));*/
                    if ("SYS_LIST_PRCSUSER1".equals(strArray[j])) {//宏控件流程设置所有经办人列表
                        //定义一个空数组
                        List<String> listR = new ArrayList<String>();
                        StringBuffer processName = new StringBuffer();
                        if (folwId != null) {
                            List<String> list = new ArrayList<String>();
                            List<FlowProcess> list1 = flowProcessMapper.findFlowId(folwId);
                            if (list1 != null) {
                                for (FlowProcess process : list1) {
                                    processName.append(flowProcessMapper.queryPrcessName(process.getFlowId(), String.valueOf(process.getPrcsId())));
                                    if (processName != null) {
                                        String[] depNa = processName.toString().split(",");
                                        for (int b = 0; b < depNa.length; b++) {
                                            String name = usersMapper.getUsernameByUserId(depNa[b]);
                                            list.add(name);
                                        }
                                    }
                                }

                                if (list != null) {
                                    for (String str : list) {
                                        //去重
                                        if (!(listR.contains(str))) {
                                            listR.add(str);
                                        }
                                    }
                                }
                            }
                            tM.setSYS_LIST_PRCSUSER1(listR);
                        }
                    }
                    if ("SYS_LIST_PRCSUSER2".equals(strArray[j])) {//宏控件本步骤设置经办人列表
                        if (folwId != null && prcsId != null) {
                            List<String> list = new LinkedList<>();
                            String processName1 = flowProcessMapper.queryPrcessName(folwId, prcsId);
                            if (processName1 != null) {
                                String[] depNa = processName1.split(",");
                                for (int b = 0; b < depNa.length; b++) {
                                    String name = usersMapper.getUsernameByUserId(depNa[b]);
                                    list.add(name);
                                }
                            }
                            tM.setSYS_LIST_PRCSUSER2(list);
                        }
                    }
                    if ("SYS_LIST_MANAGER1".equals(strArray[j])) {//宏控件-部门主管本部门
                        if (manag != null && !manag.equals("")) {
                            String[] mm = manag.split(",");
                            for (int m = 0; m < mm.length; m++) {
                                String name2 = usersService.getUserNameById(mm[m], ",");
                                List<String> lis = Arrays.asList(name2.split(","));
                                if (lis != null) {
                                    tM.setSYS_LIST_MANAGER1(lis);
                                }
                            }
                        }
                    }
                    if ("SYS_LIST_MANAGER2".equals(strArray[j])) {//宏控件-部门主管上级部门
                        //部门主管（上级部门）
                        if (department.getDeptParent() != null && !department.getDeptParent().equals("")) {
                            List<String> listC = new ArrayList<String>();
                            String parentId = departmentMapper.getDeptManagerIdByDeptId(department.getDeptParent());
                            if (parentId != null && !parentId.equals("")) {
                                String[] depNa = parentId.split(",");
                                for (int b = 0; b < depNa.length; b++) {
                                    //部门主管（上级部门主管的名称）
                                    String userName = usersService.getUserNameById(depNa[b], ",");
                                    if (userName != null && !userName.equals("")) {
                                        String[] lis = userName.split(",");
                                        for (int c = 0; c < lis.length; c++) {
                                            listC.add(String.valueOf(lis[c]));
                                        }
                                    }

                                }
                            }
                            if (listC != null) {
                                tM.setSYS_LIST_MANAGER2(listC);
                            }
                        }
                    }
                    if ("SYS_LIST_MANAGER3".equals(strArray[j])) {//宏控件-部门主管一级部门
                        //部门主管（一级部门）
                        List<Department> departments3 = departmentMapper.getDepartmentByParet();
                        List<String> listC = new ArrayList<String>();
                        if (departments3 != null) {
                            for (Department department1 : departments3) {
                                //获取所有一级部门部门主管id串
                                String deptName = departmentMapper.getDeptManagerIdByDeptId(department1.getDeptId());
                                if (deptName != null) {
                                    String[] depNa = deptName.split(",");
                                    for (int b = 0; b < depNa.length; b++) {
                                        //部门主管（一级部门主管名称）
                                        String userName = usersService.getUserNameById(depNa[b], ",");
                                        if (userName != null && !userName.equals("")) {
                                            String[] lis = userName.split(",");
                                            for (int c = 0; c < lis.length; c++) {
                                                listC.add(String.valueOf(lis[c]));
                                            }
                                        }
                                    }
                                }
                            }
                            if (listC != null) {
                                tM.setSYS_LIST_MANAGER3(listC);
                            }
                        }

                    }

                    if ("SYS_LIST_DEPT_PERSON".equals(strArray[j])) {//宏控件-本部门人员列表
                        //本部门人员列表
                        List<Users> userName = usersMapper.selectUserNameByDeptId(deptId);
                        tM.setSYS_LIST_DEPT_PERSON(userName);
                    }

                    if ("SYS_LIST_SQL".equals(strArray[j])) {//宏控件-部门主管一级部门
                        try {
                            //数据库的链接
                            Properties props = Resources.getResourceAsProperties("jdbc-sql.properties");
                            String url = props.getProperty("url" + sqlType);
                            String driver = props.getProperty("driverClassName");
                            String username = props.getProperty("uname" + sqlType);
                            String password = props.getProperty("password" + sqlType);
                            Class.forName(driver).newInstance();
                            Connection conn = (Connection) DriverManager.getConnection(url, username, password);
                            List<Map<String, Object>> isExistSql_1 = null;
                            HashMap list = new HashMap<>();
                            if (sqlList != null && !sqlList.equals("")) {
                                String[] mm = sqlList.split(";");
                                for (int o = 0; o < mm.length; o++) {
                                    String[] sqlEE = mm[o].split("-");
                                    String Data = sqlEE[0];
                                    String SqlNew = sqlEE[1];

                                    isExistSql_1 = Verification.CheckIsExistSql(request, conn, driver, url, username, password, SqlNew, runId);
                                    if (isExistSql_1 != null) {
                                        list.put(Data, isExistSql_1);
                                    }
                                }
                                tM.setSYS_LIST_SQL(list);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
           /* List<FlowRun> flowRuns = flowRunMapper.selectFromParentId(runId);
            List<FlowRunPrcs> flowRunPrcs22=new ArrayList<>();
            for (FlowRun flowRuns2:flowRuns){
                List<FlowRunPrcs> flowRunPrcs2 = flowRunPrcsMapper.selectAllByRunId(flowRuns2.getRunId());
                FlowRunPrcs flowRunPrcs3 = flowRunPrcs2.get(flowRunPrcs2.size()-1);
                Document documentModelWithBLOBs = documentMapper.selectByRunIDs(flowRuns2.getRunId()+"");
                if (documentModelWithBLOBs!=null){
                    flowRunPrcs3.setTabId(documentModelWithBLOBs.getId()+"");
                    flowRunPrcs3.setTableName("document");
                }
                flowRunPrcs22.add(flowRunPrcs3);
            }
            tM.setSYS_FLOW_CHILDFLOW(flowRunPrcs22);*/
           //lsa添加
            FlowDetailInfo attachment = flowTypeModelMapper.getAttachment(folwId);
            List<Attachment> att=new ArrayList();
            if(attachment!=null){
                if (!StringUtils.checkNull(attachment.getAttachmentId())) {//返回的附件信息
                    att=GetAttachmentListUtil.returnAttachment(attachment.getAttachmentName(), attachment.getAttachmentId(), "xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.MODULE_WORKFLOW);
                }
            }
            tM.setSYS_USERPHONE(users11.getMobilNo());//当前登陆人手机号
            tM.setSYS_FLOW_EXPLAINFILE(att);
            if(flowRun!=null){
                //关联流程
                String relationRunIds = flowRun.getRelationRunIds();//获取关联的流程数据
                if (!StringUtils.checkNull(relationRunIds)) {
                    String[] bits = relationRunIds.split(",");
                    String lastOne = bits[bits.length - 1];
                    FlowRun flowRun1 = flowRunMapper.find(Integer.parseInt(lastOne.split("\\|")[0]));
                    List<String> userIds = flowRunPrcsMapper.selectAllUserByRunId(flowRun1.getRunId());
                    StringBuffer stringBuffer = new StringBuffer();
                    for (String id : userIds) {
                        if(!id.equals(flowRun1.getBeginUser())){//排除发起人
                            stringBuffer.append(id + ",");
                        }
                    }
                    flowRun1.setAllUserName(usersService.getUserNameById(stringBuffer.toString()));
                    tM.setSYS_FLOW_CONNECTFLOW(flowRun1);
                }else{
                    tM.setSYS_FLOW_CONNECTFLOW(null);
                }
                //关联新闻---按照高总的方式加以优化。是新闻审批流程才去查询新闻表
                List<SysPara> news_approval_type = sysParaService.getTheSysParam("NEWS_APPROVAL_TYPE");//获取系统参数中的新闻审批设置
                if(news_approval_type.size()>0&&!StringUtils.checkNull(news_approval_type.get(0).getParaValue())){
                    JSONArray jsonArray = new JSONArray();
                    Map sysValues = jsonArray.parseObject(news_approval_type.get(0).getParaValue(), Map.class);//将字符串解析为map对象
                    if(String.valueOf(sysValues.get("checkType")).equals("1")){//新闻审批类型  1-流程审批    2-普通审批
                        Map newsFlow = jsonArray.parseObject(String.valueOf(sysValues.get("newsFlow")), Map.class);
                        StringBuffer str=new StringBuffer();
                        for (Object object : newsFlow.values()) {//遍历获取Map集合的value集合
                            str.append(object.toString()+",");
                        }
                        //判断当前流程是否在配置的新闻关联流程中
                        boolean flag = Arrays.asList(str.toString().split(",")).contains(String.valueOf(flowRun.getFlowId()));
                        if(flag){
                            News news = newsMapper.selectByRunId(flowRun.getRunId());
                            if(news!=null){
                                tM.setSYS_NEWS(news);
                            }else {
                                tM.setSYS_NEWS(null);
                            }
                        }
                    }
                }
            }
            json.setFlag(0);
            json.setMsg("ok");
            json.setObject(tM);
        } else {
            json.setFlag(1);
            json.setMsg("err");

        }
        return json;
    }


    @Override
    public BaseWrapper updateContent(Integer feedId, Integer signLook, String content) {
        BaseWrapper wrapper = new BaseWrapper();
        if (feedId == null) {
            wrapper.setFlag(false);
            wrapper.setStatus(true);
            wrapper.setMsg("会签意见Id不能为空");
            return wrapper;
        }
        int res = flowFormTypeMapper.updateContent(feedId, signLook, content);
        if (res > 0) {
            wrapper.setFlag(true);
            wrapper.setStatus(true);
            wrapper.setMsg("更新会签意见成功");
        } else {
            wrapper.setFlag(false);
            wrapper.setStatus(true);
            wrapper.setMsg("更新会签意见失败");
        }

        return wrapper;
    }

    @Override
    public BaseWrapper deleteContent(Integer feedId) {
        BaseWrapper wrapper = new BaseWrapper();
        if (feedId == null) {
            wrapper.setFlag(false);
            wrapper.setStatus(true);
            wrapper.setMsg("会签意见Id不能为空");
            return wrapper;
        }
        int res = flowFormTypeMapper.deleteContent(feedId);

        if (res > 0) {
            wrapper.setFlag(true);
            wrapper.setStatus(true);
            wrapper.setMsg("删除成功");
        } else {
            wrapper.setFlag(false);
            wrapper.setStatus(true);
            wrapper.setMsg("操作失败");
        }
        return wrapper;
    }


    public AjaxJson getForm(Integer flowId) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            List<FlowFormType> list = flowFormTypeMapper.getForm(flowId);
            FlowFormType flowFormType = list.get(0);
            ajaxJson.setObj(flowFormType);
            ajaxJson.setFlag(true);
            ajaxJson.setMsg("OK");
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
        }
        return ajaxJson;
    }

    public AjaxJson updateMobileDataSort(String mobileDataSort, Integer formId) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            int result = flowFormTypeMapper.updateMobileDataSort(mobileDataSort, formId);
            if (result > 0) {
                ajaxJson.setFlag(true);
                ajaxJson.setMsg("OK");
            } else {
                ajaxJson.setFlag(false);
                ajaxJson.setMsg("update false");
            }
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
        }
        return ajaxJson;
    }


    public AjaxJson getMobileDataSort(Integer formId) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            String mobileDataSort = flowFormTypeMapper.getMobileDataSort(formId);
            if (!StringUtils.checkNull(mobileDataSort)){
                ajaxJson.setFlag(true);
                ajaxJson.setMsg("OK");
                ajaxJson.setObj(mobileDataSort);
            }else {
                ajaxJson.setFlag(false);
                ajaxJson.setMsg("NULL DATA");
            }
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
        }
        return ajaxJson;
    }
}
